package com.ext.portlet.myprofile.action;


import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.UserPortraitException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.struts.PortletAction;
import com.liferay.portal.util.PortalUtil;

import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.service.ImageLocalServiceUtil;
import com.liferay.portal.service.UserServiceUtil;
import com.liferay.util.portlet.PortletRequestUtil;
import com.liferay.util.servlet.UploadException;

import java.io.File;


public class FileAction extends PortletAction {	

	public void processAction(
		ActionMapping mapping, ActionForm form, PortletConfig config,
		ActionRequest req, ActionResponse res)
			throws Exception {	
				
		try {
			updatePortrait(req);			
			sendRedirect(req, res);
		}
		catch (Exception e) {
			if (e instanceof NoSuchUserException ||
				e instanceof PrincipalException) {

				SessionErrors.add(req, e.getClass().getName());				
			}
			else if (e instanceof UploadException ||
					 e instanceof UserPortraitException) {

				SessionErrors.add(req, e.getClass().getName());
			}
			else {
				throw e;
			}
		}
			
	}		
	
	public ActionForward render(
			ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
			RenderRequest renderRequest, RenderResponse renderResponse)
		throws Exception {
		
		return mapping.findForward(getForward(
			renderRequest, "portlet.ext.myprofile.port"));
	}
	
	protected void updatePortrait(ActionRequest actionRequest)
	throws Exception {
	
		PortletRequestUtil.testMultipartWithCommonsFileUpload(
			actionRequest);	
		
	UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(
		actionRequest);

	User user = PortalUtil.getSelectedUser(uploadRequest);
	
	
	File file = uploadRequest.getFile("fileName");
	byte[] bytes = FileUtil.getBytes(file);

	if ((bytes == null) || (bytes.length == 0)) {
		throw new UploadException();
	}
	
	UserServiceUtil.updatePortrait(user.getUserId(), bytes);
}
}
